 package com.vnp.vchat.version2;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.turbomanage.httpclient.HttpResponse;
import com.vnp.vchat.MainPanelActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.Util.Common;
import com.vnp.vchat.Util.KeyboardHelper;
import com.vnp.vchat.Util.PreferenceHelper;
import com.vnp.vchat.Util.Utils;
import com.vnp.vchat.database.MySQLiteHelper;
import com.vnp.vchat.httpclient.HttpBasicClientHelper;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonAsyncCallback;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;

public class NhapPassActivity extends Activity implements OnClickListener{
	
	TextView title, titleNhapPass;
	EditText edtTk;
	Button btnTieptuc;	
	
	String name, userName;
	PreferenceHelper preferenceHelper;
	ProgressBar progressBar;
	Dialog dS;
	ArrayList<String> list = new ArrayList<String>();
	MySQLiteHelper db;

	ProgressDialog progressDialog = null;
	
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			gotoMain();
		}
	};
	Handler mHandler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_nhap_pass);
		
		preferenceHelper = new PreferenceHelper(this);
		db = new MySQLiteHelper(NhapPassActivity.this);
		
		name = getIntent().getStringExtra("name");
		userName = getIntent().getStringExtra("username");
		
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		
		title = (TextView) findViewById(R.id.title);
		titleNhapPass = (TextView) findViewById(R.id.txt_nhap_pass);
		edtTk = (EditText) findViewById(R.id.edt_mat_khau);
		btnTieptuc = (Button) findViewById(R.id.btn_tieptuc);
		
		init();
		nhapPass();
		
		setFont();
		KeyboardHelper.displaySoftKeyboard(NhapPassActivity.this, edtTk);
	}
	
	void setFont(){
		title.setTypeface(Utils.getTypefaceBold(NhapPassActivity.this));
		edtTk.setTypeface(Utils.getTypefaceRegular(NhapPassActivity.this));
		btnTieptuc.setTypeface(Utils.getTypefaceMedium(NhapPassActivity.this));
		titleNhapPass.setTypeface(Utils.getTypefaceRegular(NhapPassActivity.this));
	}
	
	void nhapPass(){
		edtTk.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_NEXT){
					checkPass();
					return true;
				}
				return false;
			}
		});
	}
	
	void init(){
		title.setText("Đăng nhập");
		titleNhapPass.setText(Html.fromHtml("Chào mừng <font color='#0070CC'>"+name+"</font>! Hãy nhập mật khẩu để tiếp tục"));
		btnTieptuc.setOnClickListener(this);
		btnTieptuc.setText("Tiếp tục");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_tieptuc:
			checkPass();
			break;
		case R.id.btn_thoat_tk:
			dS.dismiss();
			showProgressDialog();
			UpdateContactAsyn asyn = new UpdateContactAsyn();
			asyn.execute("");
			break;
		case R.id.btn_ko:
			dS.dismiss();
			mHandler.removeCallbacks(r);
			mHandler.postDelayed(r, 300);
			break;
		default:
			break;
		}
	}
	
	void checkPass(){
		if (edtTk.getText().toString().equals("")){
			Toast.makeText(NhapPassActivity.this, "Mật khẩu không được để trống!", Toast.LENGTH_SHORT).show();
		} else {
			login();
		}
	}
	
	void capnhatDanhba(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				Utils.getContact(NhapPassActivity.this);
				sendContactHttp();
			}
		}).start();
		
	}
	
	void sendContactHttp(){
		
		
		list = db.getPhoneFromDB();
		
		JSONArray jsonArray = new JSONArray(list);
		
		/*for (int i = 0; i < objContacts.size(); i++) {
			jsonArray.put(objContacts.get(i).getJSONObject());
		}*/
		
		
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				Log.i("DATA", "Cap nhat danh ba loi");
			}

			@Override
			public void onSuccess(JSONObject re) {
				Log.i("DATA", "Cap nhat danh ba thanh cong :"+re.toString());
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						Toast.makeText(NhapPassActivity.this, "Cập nhật thành công", Toast.LENGTH_SHORT).show();
					}
				});
				
				gotoMain();
			}
			
		});
		
		
		httpClientHelper.sendContact(preferenceHelper.getAdminId(), jsonArray, preferenceHelper.getHashSetting());
	}
	
	
	void showProgressDialog(){
		 progressDialog = new ProgressDialog(this);
	     progressDialog.show();        
	     progressDialog.setContentView(R.layout.custom_progress_dialog);
	     //se ppdrá cerrar simplemente pulsando back
	     progressDialog.setCancelable(false);
	     
	     new Handler().postDelayed(new Runnable() {
	         public void run() {                
	             progressDialog.dismiss();         
	         }
	     }, 90000); 
	}
	
	void login(){
		
		progressBar.setVisibility(View.VISIBLE);
		KeyboardHelper.hideSoftKeyboard(NhapPassActivity.this);
		btnTieptuc.setText("Đang đăng nhập...");
		edtTk.setEnabled(false);
		btnTieptuc.setClickable(false);
		
		
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				progressBar.setVisibility(View.GONE);
				Log.i("LOGIN", "Error: "+error.toString());
				btnTieptuc.setText("Tiếp tục");
				edtTk.setEnabled(true);
				btnTieptuc.setClickable(true);
				Toast.makeText(NhapPassActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
			}
			
			

			@Override
			@Deprecated
			public void onFailure(Throwable error, String content) {
				Log.i("LOGIN", "CONTENT: "+error.toString());
				progressBar.setVisibility(View.GONE);
				btnTieptuc.setText("Tiếp tục");
				edtTk.setEnabled(true);
				btnTieptuc.setClickable(true);
				Toast.makeText(NhapPassActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
			}



			@Override
			public void onSuccess(JSONObject re) {
				progressBar.setVisibility(View.GONE);
				Log.i("LOGIN", ""+re.toString());
				try {
					int status = re.getInt("status");
					if (status == 1){
		            	
		            	JSONObject uinf = re.getJSONObject("uinfo");
		            	JSONObject settings = re.getJSONObject("setting");
		            	
		            	preferenceHelper.setUserId(uinf.getString("use_sso_id"));
		            	preferenceHelper.setHash(re.getString("hash"));
		            	preferenceHelper.setHashSetting(re.getString("hash_setting"));
		            	preferenceHelper.setDomainConnect(re.getString("domain_connect"));
		            	preferenceHelper.setPostConnect(re.getString("port_connect"));
		            	preferenceHelper.setDataJoin(re.getString("datajoin"));
		            	preferenceHelper.setSettingNotifi(settings.getString("notifi"));
		            	preferenceHelper.setSettingFeed(settings.getString("feed"));
		            	preferenceHelper.setSettingDisplay(settings.getString("showmsg"));
		            	preferenceHelper.setUserName(uinf.getString("name"));
		            	preferenceHelper.setMyAvatar(uinf.getString("avatar"));
		            	preferenceHelper.setEmail(uinf.getString("email"));
		            	preferenceHelper.setAdminId(re.getString("admin_id"));
//		            	preferenceHelper.setPhone(value)
//		            	gotoMain();
		            	showDialogCapnhatDanhba();
		            	
		            } else if (status == 0) {
		            	progressBar.setVisibility(View.GONE);
		            	btnTieptuc.setText("Tiếp tục");
		            	edtTk.setEnabled(true);
						btnTieptuc.setClickable(true);
						Toast.makeText(NhapPassActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
		            }
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		String hash = Utils.MD5(""+Common.KEY_HTTP+"|"+""+userName+"|"+""+edtTk.getText().toString());
		
		Log.i("LOGIN", "HASH: "+hash);
		
//		httpClientHelper.loginByPhoneOrEmail(userName, edtTk.getText().toString(), hash, Common.KEY_HTTP);
		
		HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(new MyJsonAsyncCallback(){

			@Override
			public void onSuccess(HttpResponse httpResponse, JSONObject re) {
				int statusCode = httpResponse.getStatus();
				if (statusCode == 200){
					try {
						int status = re.getInt("status");
						if (status == 1){
			            	
			            	JSONObject uinf = re.getJSONObject("uinfo");
			            	JSONObject settings = re.getJSONObject("setting");
			            	
			            	preferenceHelper.setUserId(uinf.getString("use_sso_id"));
			            	preferenceHelper.setHash(re.getString("hash"));
			            	preferenceHelper.setHashSetting(re.getString("hash_setting"));
			            	preferenceHelper.setDomainConnect(re.getString("domain_connect"));
			            	preferenceHelper.setPostConnect(re.getString("port_connect"));
			            	preferenceHelper.setDataJoin(re.getString("datajoin"));
			            	preferenceHelper.setSettingNotifi(settings.getString("notifi"));
			            	preferenceHelper.setSettingFeed(settings.getString("feed"));
			            	preferenceHelper.setSettingDisplay(settings.getString("showmsg"));
			            	preferenceHelper.setUserName(uinf.getString("name"));
			            	preferenceHelper.setMyAvatar(uinf.getString("imaege"));
			            	preferenceHelper.setEmail(uinf.getString("email"));
			            	preferenceHelper.setAdminId(re.getString("admin_id"));
//			            	preferenceHelper.setPhone(value)
//			            	gotoMain();
			            	
			            	runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									showDialogCapnhatDanhba();
								}
							});
			            	
			            	
			            	
			            } else if (status == 0) {
			            	
			            	runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									progressBar.setVisibility(View.GONE);
					            	btnTieptuc.setText("Tiếp tục");
					            	edtTk.setEnabled(true);
									btnTieptuc.setClickable(true);
									Toast.makeText(NhapPassActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
								}
							});
			            }
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							progressBar.setVisibility(View.GONE);
							btnTieptuc.setText("Tiếp tục");
							edtTk.setEnabled(true);
							btnTieptuc.setClickable(true);
							Toast.makeText(NhapPassActivity.this, "Sai mật khẩu.", Toast.LENGTH_SHORT).show();
						}
					});
				}
			}

			@Override
			public void onFailure(Exception e) {
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						progressBar.setVisibility(View.GONE);
						btnTieptuc.setText("Tiếp tục");
						edtTk.setEnabled(true);
						btnTieptuc.setClickable(true);
						Toast.makeText(NhapPassActivity.this, "Đăng nhập thất bại.", Toast.LENGTH_SHORT).show();
					}
				});
			}
		});
		
		httpBasicClientHelper.loginByPhoneOrEmail(userName, edtTk.getText().toString(), hash, Common.KEY_HTTP);
		
	}
	
	void gotoMain(){
		Intent t = new Intent(NhapPassActivity.this, MainPanelActivity.class);
		finish();
		Intent broadcastIntent = new Intent();
		broadcastIntent.setAction("HUY");
		sendBroadcast(broadcastIntent);
		startActivity(t);
		overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
	}
	
	@Override
	public void onBackPressed() {
		closeActivity();
	}
	
	void closeActivity(){
		finish();
		overridePendingTransition(R.anim.over_main_right, R.anim.trans_right_out);
	}
	
	void showDialogCapnhatDanhba(){
		dS = new Dialog(this);
		dS.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dS.setContentView(R.layout.dialog_thoat_tk);
		
		
		TextView txtThoat = (TextView) dS.findViewById(R.id.str_canhbao_thoat);
		
		txtThoat.setText("Bạn có muốn đồng bộ danh bạ của bạn với vChat không?");
		
		Button btnThoat = (Button) dS.findViewById(R.id.btn_thoat_tk);
		Button btnKo = (Button) dS.findViewById(R.id.btn_ko);
		dS.show();
		dS.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dS.setCanceledOnTouchOutside(true);
		dS.getWindow().setGravity(Gravity.CENTER);
		dS.show();
		
		txtThoat.setTypeface(Utils.getTypefaceRegular(NhapPassActivity.this));
		btnThoat.setTypeface(Utils.getTypefaceRegular(NhapPassActivity.this));
		btnKo.setTypeface(Utils.getTypefaceRegular(NhapPassActivity.this));
		// setonclick
		btnThoat.setOnClickListener(this);
		btnKo.setOnClickListener(this);
	}
	
	private class UpdateContactAsyn extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			Utils.getContact(NhapPassActivity.this);
			sendContactHttp();
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					Toast.makeText(NhapPassActivity.this, "Cập nhật thành công", Toast.LENGTH_SHORT).show();
				}
			});
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
		mHandler.removeCallbacks(r);
	}
	
	
	
}
